package com.edu.danmu;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * netty弹幕服务器端
 */
public class DanmuServer {
    public static final int PORT = 8888;
    public void start(){
        System.out.println("启动弹幕服务器");
        //服务器线程组 用于接受客户端
        EventLoopGroup bossGroup = new NioEventLoopGroup(2);
        //工作线程组 用于执行IO
        EventLoopGroup workerGroup = new NioEventLoopGroup(10);
        try {
            //创建服务器的启动的对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //设置线程组
            serverBootstrap.group(bossGroup, workerGroup)
                    .option(ChannelOption.SO_BACKLOG, 1024) //设置服务器的等待队列
                    .channel(NioServerSocketChannel.class)       //设置通道类型
                    .childHandler(new ChannelInitializer<SocketChannel>() {  //创建通道的初始化器
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("http-decodec",new HttpRequestDecoder());
                            pipeline.addLast("http-aggregator",new HttpObjectAggregator(65536));
                            pipeline.addLast("http-encodec",new HttpResponseEncoder());
                            pipeline.addLast("http-chunked",new ChunkedWriteHandler());
                            pipeline.addLast("WebSocket-protocol",new WebSocketServerProtocolHandler("/ws"));
                            pipeline.addLast("WebSocket-request",new DanmuServerHandler());
                        }
                    });
            //绑定本机的端口 sync是将操作转为同步方式
            ChannelFuture sync = serverBootstrap.bind("127.0.0.1", PORT).sync();
            //关闭通道
            sync.channel().closeFuture().sync();
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            //关闭线程组
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new DanmuServer().start();
    }
}
